package com.example.composableexample

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel

/**
 * author: LiLiang
 * createTime: 2022/9/26-13:40
 * remark:
 **/

@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun HelloState() {
    val stateSimpleViewModel = viewModel<StateSimpleViewModel>()
    val stateSimple by remember {
        stateSimpleViewModel.stateSimple
    }
    Column(modifier = Modifier.padding(16.dp)) {
        Text(
            text = "Hello ${stateSimple.name}",
            modifier = Modifier.padding(bottom = 8.dp),
            style = MaterialTheme.typography.bodySmall
        )
        OutlinedTextField(
            value = stateSimple.name,
            onValueChange = { stateSimpleViewModel.updateName(it) },
            label = { Text(text = "Name") },
            colors = TextFieldDefaults.outlinedTextFieldColors(
                unfocusedBorderColor = Color.Gray,
                focusedBorderColor = Color(0xfff48fb1),
                cursorColor = Color.Magenta,
                focusedLabelColor = Color(0xfff48fb1)
            )
        )
    }
}

class StateSimpleViewModel: ViewModel() {
    val stateSimple = mutableStateOf(StateSimple())

    fun updateName(name: String) {
        stateSimple.value.name = name
    }
}

data class StateSimple(
    var id: Int = 0,
    var name: String = ""
)